package cn.kgc.rbac.shiro;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.rbac.entity.Permission;
import cn.kgc.rbac.entity.RolePers;
import cn.kgc.rbac.entity.User;
import cn.kgc.rbac.entity.UserRole;
import cn.kgc.rbac.mapper.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: mosin
 * @version: v1.0  2023/1/29
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper  userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePersMapper rolePersMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 用户授权  根据用户名查询用户权限信息   角色  权限字符串
       String primaryPrincipal = (String) principals.getPrimaryPrincipal();
       // 根据用户名 查询用户id
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", primaryPrincipal));
        Integer userId = user.getId();

        //根据用户id  查询用户角色id
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", userId));
        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());

        // 根据用户角色id 查询角色名称
        List<String> roles = roleMapper.selectBatchIds(roleIds).stream().map(role -> {
            return role.getRoleName();
        }).collect(Collectors.toList());

        // 角色授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);

        // 根据角色id  查询角色权限关联表
        List<RolePers> rolePers = rolePersMapper.selectList(new QueryWrapper<RolePers>().in("role_id", roleIds));

        List<Integer> perIds = rolePers.stream().map(rp -> {
            return rp.getPerId();
        }).collect(Collectors.toList());

        //根据权限id查询权限详细信息
        List<Permission> permissions = permissionMapper.selectBatchIds(perIds);

        List<String> collect = permissions.stream().map(permission -> {
            return permission.getPermission();
        }).collect(Collectors.toList());

        // 添加权限字符串
        simpleAuthorizationInfo.addStringPermissions(collect);

        return simpleAuthorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken  = (UsernamePasswordToken)token;
        String username = usernamePasswordToken.getUsername();
        //根据用户名查询数据库
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername,username);  //  select *  from  user   where username = username
        User user = userMapper.selectOne(lambda);

        if(ObjectUtil.isNotNull(user)){
            if(user.getState()==0){
                throw  new LockedAccountException();
            }else{
                return  new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
            }
        }
        return null;
    }
}
